<?php //pack11class

class VisitObjectResponder extends Module {

    public function setup() {

        $captchaTest=MySQLGet::process("Select `number` from ".MySQL::TABLE_CAPTCHA." where MD5(`hash`)='".$_POST['cid']."' limit 1;");
        $captcha=$captchaTest[0]['number'];
        if($captcha!=$_POST['c_value']) {
            //echo $captcha." ".$_POST['c_value']." ".MySQLGet::getQuery()."<br/>";
            $this->setBody(LabelManager::getLabel("popup_visit_wrong"));
            return false;
        }

        $dekaro=$this->sendDekaro();
        $visitor=$this->sendVisitor();
        if($dekaro && $visitor) {
            $this->setBody(LabelManager::getLabel("popup_visit_response")."::".LabelManager::getLabel("done_preview"));
        } else {
            $this->setBody(LabelManager::getLabel("popup_visit_wrong"));
        }
        $sms=$this->sendSMS();
        $sms=true;
        if(!$sms) {
            $this->sendError();
        }
    }

    private function sendError() {
        return $this->processMail(array("vit@balticom.lv"),implode("; ",$_POST),"DEKARO SMS ERROR");
    }

    private function sendDekaro() {

        $text="Name желает посмотреть объект [id] address<BR>Желаемое время: day, time<BR><BR>Телефон: phone<BR>E-mail:_mail";

        if(array_key_exists("address", $_POST)) {
            $text=str_replace("address", $_POST["address"], $text);
        }
        if(array_key_exists("name", $_POST)) {
            $text=str_replace("Name", $_POST["name"], $text);
        }

        if(array_key_exists("day", $_POST)) {
            $text=str_replace("day", $_POST["day"], $text);
        }

        if(array_key_exists("phone", $_POST)) {
            $text=str_replace("phone", $_POST["phone"], $text);
        }
        if(array_key_exists("mail", $_POST)) {
            $text=str_replace("_mail", $_POST["mail"], $text);
        }
        if(array_key_exists("id", $_POST)) {
            $text=str_replace("id", $_POST["id"], $text);
        }
        if(array_key_exists("time_from", $_POST) && array_key_exists("time_to", $_POST)) {
            if($_POST["time_from"]=="after"){
                $from=$_POST["time_to"];
                $to="21:00";
            } else {
                $from=$_POST["time_from"];
                $to=$_POST["time_to"];
            }
            $text=str_replace("time", $from." - ".$to, $text);
        }

        return $this->processMail(array("dekaro@dekaro.lv"),$text,"DEKARO POTENTIAL CLIENT");
        //return $this->processMail(array("dekaro6611@com.lmt.lv"),$text,"DEKARO POTENTIAL CLIENT");
    }

    private function sendVisitor() {

        $text=LabelManager::getLabel("visitor_mail_response")."<br><br>-------------------<br>%data%<br><br>-------------------<br>".LabelManager::getLabel("mail_bug_report");
        $time=array();
        $mail="vit@balticom.lv";
        $address="";
        $data=array();

        if(array_key_exists("address", $_POST)) {
            $text=str_replace("%address%", $_POST["address"], $text);
            $address=$_POST["address"];
            array_push($data,$_POST["address"]);
        }

        if(array_key_exists("name", $_POST)) {
            array_push($data,$_POST["name"]);
        }

        if(array_key_exists("day", $_POST)) {
            array_push($time,$_POST["day"]);
        }

        if(array_key_exists("phone", $_POST)) {
            $text=str_replace("phone", $_POST["phone"], $text);
            array_push($data,$_POST["phone"]);
        }
        if(array_key_exists("mail", $_POST)) {
            array_push($data,$_POST["mail"]);
            $mail=$_POST["mail"];
        }
        if(array_key_exists("time_from", $_POST) && array_key_exists("time_to", $_POST)) {
            if($_POST["time_from"]=="after"){
                $from=$_POST["time_to"];
                $to="21:00";
            } else {
                $from=$_POST["time_from"];
                $to=$_POST["time_to"];
            }
            array_push($time,$from." - ".$to);
        }

        $text=str_replace("%data%", implode("<br>", $data), $text);
        $text=str_replace("%time%", implode(", ", $time), $text);

        return $this->processMail(array($mail),$text,"DEKARO");
    }

    private function sendSMS() {
        $res=array();
        if(array_key_exists("address", $_POST)) {
            $adr=explode(", ",$_POST["address"]);
            array_push($res,$adr[count($adr)-2].", ".$adr[count($adr)-1]);
        }
        if(array_key_exists("name", $_POST)) {
            array_push($res,$_POST["name"]);
        }
        if(array_key_exists("phone", $_POST)) {
            array_push($res,$_POST["phone"]);
        }
        if(array_key_exists("day", $_POST)) {
            array_push($res,$_POST["day"]);
        }

        if(array_key_exists("time_from", $_POST) && array_key_exists("time_to", $_POST)) {
            $from=$_POST["time_from"];
            $to=$_POST["time_to"];
            if($_POST["time_from"]=="after"){
                $from=$_POST["time_to"];
                $to="21:00";
            } else {
                $from=$_POST["time_from"];
                $to=$_POST["time_to"];
            }
            array_push($res,$from."-".$to);
        }
        //echo $this->encodestring(implode(";",$res));
        //"+37129275845@sms.lmt.lv"
        //return $this->processMail(array("dekaro@sms.lmt.lv"),$this->encodestring(implode("; ",$res))," ",false);
        return $this->processMail(array("dekaro6611@sms.lmt.lv"),$this->encodestring(implode("; ",$res))," ",false);
    }

    private function processMail($mails,$body,$subject,$useHeaders=true) {

        $email = "client@dekaro.lv";

        $dodgy_strings = array(
                "content-type:"
                ,"mime-version:"
                ,"multipart/mixed"
                ,"bcc:"
        );

        if($_SERVER['REQUEST_METHOD'] != "POST"){
            echo("Unauthorized attempt to access page.");
            exit;
        }

        if (!$this->is_valid_email($email)) {
            echo 'Invalid email submitted - mail not being sent.';
            exit;
        }

        $this->contains_bad_str($email);
        $this->contains_bad_str($subject);
        $this->contains_bad_str($body);
        $this->contains_newlines($email);
        $this->contains_newlines($subject);

        $headers="From: $email\r\n";
        if($useHeaders) $headers.="Content-type: text/html; charset=UTF-8\r\n";
        
        foreach($mails as $to) {
          //echo $to."\n";
          if(mail($to, $subject, $body, $headers)) {
              //echo $to."\n";
          } else {
              return false;
          }
        }

        //echo $body."\n";

        return true;

}

private function is_valid_email($email) {
  return preg_match('#^[a-z0-9.!\#$%&\'*+-/=?^_`{|}~]+@([0-9.]+|([^\s]+\.+[a-z]{2,6}))$#si', $email);
}

private function contains_bad_str($str_to_test) {
  $bad_strings = array(
                "content-type:"
                ,"mime-version:"
                ,"multipart/mixed"
		,"Content-Transfer-Encoding:"
                ,"bcc:"
		,"cc:"
		,"to:"
  );

  foreach($bad_strings as $bad_string) {
    if(eregi($bad_string, strtolower($str_to_test))) {
      echo "$bad_string found. Suspected injection attempt - mail not being sent.";
      exit;
    }
  }
}

private function contains_newlines($str_to_test) {
   if(preg_match("/(%0A|%0D|\\n+|\\r+)/i", $str_to_test) != 0) {
     echo "newline found in $str_to_test. Suspected injection attempt - mail not being sent.";
     exit;
   }
}


private function encodestring($st)  {
$tr = array(
 "Ґ"=>"G","Ё"=>"E","Є"=>"E","Ї"=>"YI","І"=>"I",
 "і"=>"i","ґ"=>"g","ё"=>"e","№"=>"#","є"=>"e",
 "ї"=>"yi","А"=>"A","Б"=>"B","В"=>"V","Г"=>"G",
 "Д"=>"D","Е"=>"E","Ж"=>"Zh","З"=>"Z","И"=>"I",
 "Й"=>"J","К"=>"K","Л"=>"L","М"=>"M","Н"=>"N",
 "О"=>"O","П"=>"P","Р"=>"R","С"=>"S","Т"=>"T",
 "У"=>"U","Ф"=>"F","Х"=>"H","Ц"=>"C","Ч"=>"Ch",
 "Ш"=>"Sh","Щ"=>"Sch","Ъ"=>"'","Ы"=>"Y","Ь"=>"",
 "Э"=>"E","Ю"=>"Ju","Я"=>"Ja","а"=>"a","б"=>"b",
 "в"=>"v","г"=>"g","д"=>"d","е"=>"e","ж"=>"zh",
 "з"=>"z","и"=>"i","й"=>"j","к"=>"k","л"=>"l",
 "м"=>"m","н"=>"n","о"=>"o","п"=>"p","р"=>"r",
 "с"=>"s","т"=>"t","у"=>"u","ф"=>"f","х"=>"h",
 "ц"=>"c","ч"=>"ch","ш"=>"sh","щ"=>"sch","ъ"=>"'",
 "ы"=>"y","ь"=>"","э"=>"e","ю"=>"ju","я"=>"ja"
 );
 return strtr($st,$tr);
  }
  
}
?>
